package Demo3;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: homechen
 * Date: 2024-03-24
 * Time: 12:58
 */
class Person {
    private int age;
    private String name;

    public Person() {

    }

    public Person(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public void sayHi() {
        System.out.println("你好 " + name + " 年纪 " + age);
    }
}

public class ReflectionExample {
    public static void main(String[] args) throws Exception {

        Class<?> myclass = Person.class;

        ClassLoader classLoader = ClassLoader.getSystemClassLoader(); // 获取系统加载器
        Class<?> myclass1 = classLoader.loadClass("Demo3.Person");

        // 获取 Person 类的 class
        Class<?> personClass = Class.forName("Demo3.Person");
        // 获取类名
        System.out.println("类名：" + personClass.getName());
        // 获取类的所有字段
        System.out.println("字段列表：");
        Field[] fields = personClass.getDeclaredFields();
        for (Field field : fields) {
            System.out.println(" " + field.getName());
        }
        // 获取类的所有方法
        System.out.println("方法列表：");
        Method[] methods = personClass.getDeclaredMethods();
        for (Method method : methods) {
            System.out.println(" " + method.getName());
        }
        // 获取构造方法
//        Constructor<Person> constructor = personClass.
//                getDeclaredConstructor(int.class, String.class);// 指定构造方法参数
//        // 如果构造方法是私有，就需要进行设置
//        constructor.setAccessible(true);
//        Person person = constructor.newInstance(80, "小米");
//        person.sayHi();
    }
}
